package com.jackrain.nea.fc.cp.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.CadUserSaveCmd;
import com.jackrain.nea.fc.cp.adutils.AdUser;
import com.jackrain.nea.fc.cp.mapper.CadorgMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * Created by ZCY on 2017/12/16.
 * 新增修改AD域用户，修改AD域用户
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "cp")
public class CadUserSaveCmdImpl extends CommandAdapter implements CadUserSaveCmd {
    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH-mm-ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (param == null) {
            throw new NDSException("请选择需要同步的用户！");
        }
        CadorgMapper cadorgMapper = ApplicationContextHandle.getBean(CadorgMapper.class);
        JSONArray Idsary = param.getJSONArray("IDS");
        Boolean idsbol = Idsary == null || (Idsary != null && Idsary.size() == 0);
        if (idsbol) {
            throw new NDSException("请传入用户IDS数组");
        }
        AdUser.ldapload();
        JSONArray dataary = new JSONArray();
        Boolean backbol = true;
        for (int i = 0; i < Idsary.size(); i++) {
            Long objid = Idsary.getLong(i);
            String cn = null;
            try {

                JSONObject usershash = cadorgMapper.findhuseratu(objid);
                if (usershash == null) {
                    JSONObject cnullobj = new JSONObject(true);
                    cnullobj.put("org", "ID=" + objid + " 没有ADYU=Y的数据");
                    dataary.add(cnullobj);

                } else {
                    //手机号去空格
                    //usershash.put("mobile",usershash.getString("mobile").trim());
                    Long Hrorgid = TypeUtils.castToLong(usershash.get("CP_C_HRORG_ID"));
                    String Isenabled = TypeUtils.castToString(usershash.get("ISENABLED"));
                    Long Cstoreid = TypeUtils.castToLong(usershash.get("CP_C_STORE_ID"));
                    //查询STORENATUR如果STORENATURE='STO'所属组织传店铺编码

                    cn = TypeUtils.castToString(usershash.get("cn"));

                    if (Hrorgid == null) {
                        throw new NDSException("该用户没有所属组织");
                    }
                    if ("1".equals(Isenabled)) {
                        Long adorgid = Hrorgid;
                        Boolean existbol = true;
                        StringBuffer hrogbuf = new StringBuffer("");


                        if (Cstoreid != null) {


                            String storeNature = cadorgMapper.findstorenature(Cstoreid);

                            if ("STO".equals(storeNature)) {

                                HashMap storenamehash = cadorgMapper.findstore(Cstoreid);
                                String storename = TypeUtils.castToString(storenamehash.get("ENAME"));
                                hrogbuf.append("OU=").append(storename).append(",");

                            }

                        }

                        do {
                            HashMap horoghash = cadorgMapper.findorgin(adorgid);
                            if (horoghash == null) {
                                throw new NDSException("组织ID=" + adorgid + "当前记录已不存在！");
                            }
                            Long CpcOrgupid = TypeUtils.castToLong(horoghash.get("CP_C_ORGUP_ID"));
                            String horgEname = TypeUtils.castToString(horoghash.get("ENAME"));
                            hrogbuf.append("OU=").append(horgEname).append(",");
                            if (CpcOrgupid == null) {
                                existbol = false;
                            }
                            adorgid = CpcOrgupid;
                        }
                        while (existbol);


//                        log.info(hrogbuf + "====hrogbuf====");
                        hrogbuf.deleteCharAt(hrogbuf.length() - 1);
                        String strhrorg = hrogbuf.toString();

                        strhrorg = strhrorg.replaceAll("[/\\\\]", "|");

                        Long empid = usershash.getLong("CP_C_EMP_ID");
                        String Title = null;
                        usershash.put("Title", Title);
                        if (empid != null) {

                            HashMap jobenamehash = cadorgMapper.findjobename(empid);
                            if (jobenamehash != null) {
                                Title = TypeUtils.castToString(jobenamehash.get("EMP_POST"));
                                usershash.put("Title", Title);
                            }
                        }
                        usershash.remove("CP_C_HRORG_ID");
                        usershash.remove("CP_C_EMP_ID");
                        usershash.remove("CP_C_STORE_ID");
                        usershash.remove("ISENABLED");
                        usershash.put("fatherName", strhrorg);
                        AdUser.acceptUser(usershash);
                        JSONObject successtobj = new JSONObject(true);
                        successtobj.put("org", cn);
                        dataary.add(successtobj);
                    } else {

                        JSONObject disobj = cadorgMapper.findusersel(objid);
                        String Title = null;
                        disobj.put("Title", Title);
                        Long cpempid = disobj.getLong("CP_C_EMP_ID");
                        if (cpempid != null) {
                            HashMap disjobnamehash = cadorgMapper.findjobename(cpempid);
                            if (disjobnamehash != null) {
                                Title = TypeUtils.castToString(disjobnamehash.get("EMP_POST"));
                                disobj.put("Title", Title);
                            }
                        }
                        disobj.remove("CP_C_EMP_ID");
                        cn = TypeUtils.castToString(usershash.get("cn"));
                        JSONObject userobj = new JSONObject(true);
                        userobj.put("sAMAccountName", cn);
                        AdUser.disableUser(userobj, disobj);
                        JSONObject suboj = new JSONObject(true);
                        suboj.put("org", cn);
                        dataary.add(suboj);
                    }
                }
            } catch (Exception et) {
                JSONObject exobj = new JSONObject(true);
                exobj.put("org", cn);
                exobj.put("error", et.getMessage());
                dataary.add(exobj);
                backbol = false;
            }

        }
        if (backbol) {
            vh.put("code", 0);

        } else {
            vh.put("code", -1);
        }

        vh.put("message", dataary);
        AdUser.closeCtx();
        return vh;
    }
}
